<?php

namespace App\Services;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Order;

class PayService
{
    protected $pay;
    public function __construct()
    {
        $this->setPay();
    }

    public function setPay()
    {
        $this->pay = app('wechat.payment');
    }

    public function getPay()
    {
        return $this->pay;
    }

    public function getConfig($body, $tradeno, $fee, $openid)
    {
        $app = $this->pay;
        $result = $app->order->unify([
            'body' => $body,
            'out_trade_no' => $tradeno,
            'total_fee' => $fee * 100,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            //保存prepayID用于发送模板消息
            // $preid = new WechatRoutineFormid();
            // $preid->openid = $openid;
            // $preid->prepayId = $result['prepay_id'];
            // $preid->save();
            //
            $prepayId = $result['prepay_id'];
            $jssdk = $app->jssdk;
            $config = $jssdk->sdkConfig($prepayId); // 返回数组
            $res['code'] = 'success';
            $res['data'] = $config;
            return $res;
        }

        if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
            $res['code'] = 'fail';
            $res['data'] = $result['return_msg'];
            return $res;
        }
    }

    /***
     *
     * 自定义回调中的处理函数
     *
     *
     */
    public function payAfter($message)
    {
        $order = Order::where('no', $message['out_trade_no'])->first();
        // 将订单标记为已支付
        $order->update([
            'paid_at' => Carbon::now(),
            'payment_method' => 'wechat',
            'payment_no' => $message['transaction_id'],
        ]);

        // $user = User::where('openid', $message['openid'])->first();
        // $userbill = new UserBill([
        //     'user_id' => $user->id,
        //     'pm' => 1,
        //     'title' => '零钱充值',
        //     'category' => 'money',
        //     'type' => 'recharge',
        //     'balance' => $user->money,
        //     'number' => $message['total_fee'] / 100,
        //     'trade_no' => $message['out_trade_no'],
        //     'transaction_id' => $message['transaction_id'],
        //     'status' => 1,
        //     'pay_time' => Carbon::now(),
        // ]);
        // $userbill->save();
        // $user->money = ($user->money * 100 + $message['total_fee']) / 100;
        // $user->save();
    }

    //钱包充值回调后处理函数
    // public function rechargeAfter($message)
    // {
    //     $user = User::where('openid', $message['openid'])->first();
    //     $userbill = new UserBill([
    //         'user_id' => $user->id,
    //         'pm' => 1,
    //         'title' => '零钱充值',
    //         'category' => 'money',
    //         'type' => 'recharge',
    //         'balance' => $user->money,
    //         'number' => $message['total_fee'] / 100,
    //         'trade_no' => $message['out_trade_no'],
    //         'transaction_id' => $message['transaction_id'],
    //         'status' => 1,
    //         'pay_time' => Carbon::now(),
    //     ]);
    //     $userbill->save();
    //     $user->money = ($user->money * 100 + $message['total_fee']) / 100;
    //     $user->save();
    // }

    // //洗车支付处理响应
    // public function washPayAfter($order_sn, $transaction_id = "0")
    // {
    //     $res = WashOrder::where(array('order_sn' => $order_sn))->first();
    //     Log::info('洗车支付成功');
    //     if ($res && 0 == $res['pay_status']) {
    //         //增加支付记录
    //         // 增加 transaction_id
    //         WashOrder::where(array('order_sn' => $order_sn))->update(array('pay_status' => 1, 'transaction_id' => $transaction_id,'paytype'=>'wechat'));
    //         //用掉优惠券
    //         if ($res['wash_coupon_id'] > 0) {
    //             WashCouponUser::use_coupon_id($res['wash_coupon_id']);
    //         }
    //         Log::info($res['money']);
    //         if($res['money']!=0)
    //         {
    //             //计算佣金
    //             $calcMoney = new SeparateMoneyService();
    //             $calcMoney->separate_money($order_sn);
    //         }
    //         $package_id = $res->package_id;
    //         $time = WashMachinePackage::find($package_id)->wash_time;
    //         $this->sendStart($res->mac_id,$time);
    //     }
    // }

    // //发送启动机器指令
    // public function sendStart($mac_id,$time)
    // {
    //     $url ='http://ctp.uberu.vip/washcar/nc/api/machine/start';
    //     $username = config('site.machine_api_request_name');
    //     $pass = config('site.machine_api_request_pass');
    //     $arr_header[] = "Content-Type:application/json";
    //     $arr_header[] = "Authorization: Basic ".base64_encode($username.':'.$pass); //添加头，在name和pass处填写对应账号密码
    //     $data['mac_id'] = $mac_id;
    //     $data['time'] = $time*60;
    //     $res = CurlService::httpRequest($url,'POST',\GuzzleHttp\json_encode($data),$arr_header);
    //     Log::info($res);
    // }
    // //VIP充值回调处理
    // public function vipRechargeAfter($message)
    // {
    //     $user = User::where('openid', $message['openid'])->first();
    //     $trade_no = $message['out_trade_no'];
    //     $viplog = UserVipLog::where('trade_no',$trade_no)->first();
    //     if(!empty($viplog))
    //     {
    //         $viplog->transaction_id = $message['transaction_id'];
    //         $viplog->is_valid = 1;
    //         $viplog->save();
    //         $this->sendMsg($user,$viplog->formid,$viplog->money,$viplog->expire_time);
    //     }
    //     $vipService = new VipService();
    //     $vipService->addVip($user,$viplog->add_days);
    //     //充值vip是否送分享券
    //     $if_send_coupon = GiveVipSharecouponEverymonth::first()->value('enabled');
    //     if($if_send_coupon)
    //     {
    //         $couponService = new CouponService();
    //         $couponService->giveShareCoupons($user);
    //     }
    // }

    // //设备出资充值后
    // public function FunderRechargeAfter($message)
    // {
    //     $user = User::where('openid', $message['openid'])->first();
    //     $trade_no = $message['out_trade_no'];
    //     $funderlog = UserFunderLog::where('trade_no',$trade_no)->first();
    //     if(!empty($funderlog))
    //     {
    //         $funderlog->transaction_id = $message['transaction_id'];
    //         $funderlog->save();
    //         $washfunder = new WashMachineFunder();
    //         $washfunder->user_id = $user->id;
    //         $washfunder->region = $funderlog->region;
    //         $washfunder->expire_time = Carbon::now()->addYears(3);
    //         $washfunder->state = 1;
    //         $washfunder->save();
    //         //修改已经出资人数量
    //         $washfunderregion = WashMachineFunderRegion::where('region',$funderlog->region)->first();
    //         $washfunderregion->current_numbers = $washfunderregion->current_numbers+1;
    //         $washfunderregion->save();
    //     }
    // }
    // //购买优惠券回调
    // public function BuyCouponAfter($message)
    // {
    //     $trade_no = $message['out_trade_no'];
    //     $log = WashCouponCanshareRechargeLog::where('trade_no',$trade_no)->first();
    //     if(!empty($log))
    //     {
    //         $log->transaction_id = $message['transaction_id'];
    //         $log->save();
    //     }
    //     //判断数据库有没有该优惠券
    //     $exist = UserCanshareCoupon::where(['user_id'=>$log->user_id,'coupon_id'=>$log->coupon_id])->first();
    //     $num = $log->num;
    //     if(!empty($exist))
    //     {
    //         $num = $exist->num + $log->num;
    //     }
    //     $user_cansharecoupn = [
    //         'coupon_id' => $log->coupon_id,
    //         'num'=>$num,
    //         'coupon_title'=>$log->coupon_title,
    //         'title'=>$log->description,
    //     ];
    //     UserCanshareCoupon::updateOrCreate(['user_id' => $log->user_id,'coupon_id'=>$log->coupon_id],$user_cansharecoupn);
    //     //用户的优惠券记录表
    //     $user_sharecoupnlog = new UserCanshareCouponLog();
    //     $user_sharecoupnlog->user_id = $log->user_id;
    //     $user_sharecoupnlog->coupon_id = $log->coupon_id;
    //     $user_sharecoupnlog->type = 'recharge';
    //     $user_sharecoupnlog->pm = 1;
    //     $user_sharecoupnlog->num = $log->num;
    //     $user_sharecoupnlog->save();
    // }
    // //发送模板消息
    // protected function sendMsg($user, $formid, $money, $expire)
    // {
    //     /*
    //     会员名称：{{keyword1.DATA}}
    //     支付金额：{{keyword3.DATA}}
    //     到期时间：{{keyword2.DATA}}
    //     开通状态：{{keyword4.DATA}}
    //      */
    //     $template_id = WechatRoutineTemplate::where(['tempkey' => 'T_GET_VIP', 'status' => 1])->value('tempid');
    //     if (!empty($template_id)) {
    //         $data = [
    //             'keyword1' => '充值VIP会员成功',
    //             'keyword2' => $money . '元',
    //             'keyword3' => $expire,
    //             'keyword4' => '已开通',
    //         ];
    //         $message_service = new TemplateMessageService();
    //         $message_service->send($user->openid, $template_id, '/pages/index/index', $formid, $data);
    //     }
    // }

}
